package gameengine;

import gameengine.map.Action;
import gameengine.map.Map;
import gameengine.map.MapInstance;
import gameengine.opponents.AbstractOpponent;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

public final class Core extends Observable implements Observer {
    // private transient int round;
    private final transient int numberPlayers;
    private final transient List<MapInstance> screens;

    private static final transient boolean WAIT = false;
    private final transient Map map;

    public Core(final MapProperty mapproperty, final List<AbstractOpponent> opponents) {
        super();

        this.numberPlayers = mapproperty.getNumberPlayers();
        map = mapproperty.getMap();
        this.screens = new ArrayList<MapInstance>();

        if (opponents.size() != this.numberPlayers) {
            throw new IllegalArgumentException("Wrong number of Players! (" + opponents.size() + "/" + this.numberPlayers + ")");
        }

        for (final AbstractOpponent opp : opponents) {
            opp.addObserver(this);
            opp.setMap(map);
        }

        addObserver(map);
    }

    public void addObserver(final MapInstance observer) {
        super.addObserver(observer);
        this.screens.add(observer);
    }

    public int getNumberPlayers() {
        return this.numberPlayers;
    }

    public Map getMap() {
        return map;
    }

    public void update(final Observable caller, final Object argument) {
        if (argument instanceof Action) {
            final Action action = (Action) argument;
            // if ((this.round % this.numberPlayers) == action.getParty()) {
            for (final MapInstance mi : this.screens) {
                while (!mi.isReady()) {
                    if (!WAIT) {
                        return;
                    }
                }
            }
            setChanged();
            notifyObservers(action);
        }
        // }
    }
}
